package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetMgrChatList(param map[string]interface{}, order string, page, size int) ([]*models_main.MgrChat, error) {
	fName := "GetMgrChatList"
	o := make([]*models_main.MgrChat, 0)
	table := mysql.GetRTable(&models_main.MgrChat{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetMgrChat(param map[string]interface{}) (*models_main.MgrChat, error) {
	fName := "GetMgrChat"
	o := &models_main.MgrChat{}
	table := mysql.GetRTable(&models_main.MgrChat{})
	mysql.Condition(table, param, "", "id desc", 0, 0)
	err := table.Take(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return o, nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertMgrChat(MgrChat *models_main.MgrChat) error {
	fName := "InsertMgrChat"
	err := global.GetX().Create(MgrChat).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateMgrChat(columns []string, MgrChat *models_main.MgrChat) error {
	fName := "UpdateMgrChat"
	err := global.GetX().
		Model(MgrChat).
		Select(columns).
		Updates(MgrChat).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func DeleteMgrChat(MgrChat *models_main.MgrChat) error {
	fName := "DeleteMgrChat"
	err := global.GetX().Delete(MgrChat, MgrChat.Id).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
